package com.onion.codegen.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class TemplateUtil {

	private TemplateUtil() {
	}

	private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

	static {
		// 这里比较重要，用来指定加载模板所在的路径
		CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(TemplateUtil.class, "/template"));
		CONFIGURATION.setDefaultEncoding("UTF-8");
		CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
	}

	public static Template getTemplate(String templateName) throws IOException {
		try {
			return CONFIGURATION.getTemplate(templateName);
		} catch (IOException e) {
			throw e;
		}
	}

	public static void clearCache() {
		CONFIGURATION.clearTemplateCache();
	}

	public static void createTemplateFile(boolean force, String templateName, String filePath,Map<String, Object> dataMap) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			file.getParentFile().mkdirs();
		}else if(!force){//文件已存在并且强制写入为false
			return;
		}
		file.getParentFile().mkdirs();
		
		Template template = getTemplate(templateName);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		Writer out = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "UTF-8"), 1024);
		template.process(dataMap, out);
	}

}
